import EventEmitter from "events";
import SelectionModel from "../models/selection_model";

export class RenderView extends EventEmitter{
  [x: string]: any;
  private textModel_;
  private selectionModel_;
  private viewContainer_;
  constructor(textModel: any, selectionModel: SelectionModel, viewContainer: HTMLElement) {
    super()
    this.textModel_ = textModel;
    this.selectionModel_ = selectionModel;
    this.viewContainer_ = viewContainer;
    this.addEventListener();
  }
  /**
   * @description 监听事件的触发 更新页面
   */
  addEventListener() {
    this.textModel_.on('text-change', this.render.bind(this))
    window.document.addEventListener('selectionchange', this.domSelectionChangeHandler.bind(this))
  }
  domSelectionChangeHandler () {
    const domSelection = window.getSelection()
    if (domSelection) {
      this.emit('selection-change', {anchor: domSelection.anchorOffset, focus: domSelection.focusOffset})
    }
  }
  /**
   * @description 更新dom的选择
   */
  updateDomSelection(){
    const domSelection =window.getSelection()
    if(domSelection){
      const selectionFromModel = this.selectionModel_.getSelection()
      const anchor = selectionFromModel.anchor
      const range = window.document.createRange()
      range.setStart(this.viewContainer_.childNodes[0], anchor)
      range.setEnd(this.viewContainer_.childNodes[0], anchor)
      domSelection.removeAllRanges()
      domSelection.addRange(range)
    }
  }
  /**
   * @description 渲染
   */
  render(){
    this.viewContainer_.innerHTML = this.textModel_.getSpacers() + '\n';
    // 使用 promise 的微任务 代替 setTimeout，
    // 因为 setTimeout 会有4ms的延时，导致光标一直在 首位 闪烁
    // 而 promise的then是微任务，会在当前次的宏任务结束之后 立马执行 就不会出现闪烁的问题了
     Promise.resolve().then(()=>{
     this.updateDomSelection() 

    })
    // setTimeout(()=>{
    // })
  }
}